package com.tsing.cedap.common.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgentUtil;
import com.tsing.cedap.common.service.ILogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Order(2)
@Component
public class LogAspect {

    @Value("${frame.log.support:false}")
    private String logSupport;

    @Autowired
    private ILogService logService;

    @Pointcut("@annotation(com.tsing.cedap.common.annotations.SystemLog)")
    public void logPointCut() {
    }

    @AfterReturning("logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint) {
        if ("true".equals(logSupport)) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String userAgent = request.getHeader("User-Agent");
            String browser = StrUtil.isBlank(userAgent) ? null : UserAgentUtil.parse(userAgent).getBrowser().toString();
            logService.save(request.getHeader("token"), ServletUtil.getClientIP(request), browser, request.getServletPath(), joinPoint, null);
        }
    }

    @AfterThrowing(value = "logPointCut()", throwing = "exception")
    public void doAfterThrowing(JoinPoint joinPoint, Exception exception) {
        if ("true".equals(logSupport)) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String userAgent = request.getHeader("User-Agent");
            String browser = StrUtil.isBlank(userAgent) ? null : UserAgentUtil.parse(userAgent).getBrowser().toString();
            logService.save(request.getHeader("token"), ServletUtil.getClientIP(request), browser, request.getServletPath(), joinPoint, exception);
        }
    }

}
